package service

import (
	"cgs-server/server/cgs/app/models"
	v1 "cgs-server/server/cgs/app/models/v1"
	"cgs-server/server/cgs/app/models/vo"
	"cgs-server/server/cgs/app/store"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type MarketSrv interface {
	List(user *model.User) (*vo.MarketList, error)
	Detail(id string, user *model.User) (*vo.Market, error)
	Delete(id string, user *model.User) error
	Save(wg *models.Market, user *model.User) error
	Update(wg *models.Market, user *model.User) error
}

type marketSrv struct {
	store store.Factory
}

func (w *marketSrv) Update(wg *models.Market, user *model.User) error {
	err := w.store.Market().Update(wg, user, v1.UpdateOptions{})
	return err
}

func (w *marketSrv) Save(wg *models.Market, user *model.User) error {
	err := w.store.Market().Save(wg, user, v1.CreateOptions{})
	if err != nil {
		return err
	}

	return nil
}

func (w *marketSrv) Delete(id string, user *model.User) error {
	objId, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return err
	}
	err = w.store.Market().Delete(&models.Market{Id: objId}, user, v1.DeleteOptions{})
	return err
}

func (w *marketSrv) Detail(id string, user *model.User) (*vo.Market, error) {
	// 1. 查询分组信息
	objId, err := primitive.ObjectIDFromHex(id)
	if err != nil {
		return nil, err
	}
	wg := models.Market{Id: objId}
	market, err := w.store.Market().Get(&wg, user, v1.GetOptions{})
	if err != nil {
		return nil, err
	}
	return market, err
}

func (w *marketSrv) List(user *model.User) (*vo.MarketList, error) {
	wg := models.Market{}
	opts := v1.ListOptions{}
	list, err := w.store.Market().List(&wg, user, opts)
	return list, err
}

func newMarketSrv(s *service) MarketSrv {
	return &marketSrv{
		store: s.store,
	}
}
